import Cookies from 'js-cookie'
import routes from '@/router/routes'
// import { getMenuByRouter } from '@/router/util'
import { getStorage, setStorage } from '@/utils/storage'
import { getAuthorityMenuList } from '@/api/manager'
import { filterAsyncRouter, filterRouteKeys } from '@/router/util'
import { asyncRouterMap } from '@/router/routes'
const app = {
  state: {
    sidebar: {
      opened: !+Cookies.get('sidebarStatus'),
      withoutAnimation: false
    },
    language: Cookies.get('language') || 'zh',
    visitedViews: [],
    cachedViews: [],
    menus: [],
    disqualificationId: ''      //不合格记录ID
  },
  getters: {
    menus: state => filterRouteKeys(state.menus),
    sidebar: state => state.sidebar,
    language: state => state.language,
    visitedViews: state => state.visitedViews,
    cachedViews: state => state.cachedViews
  },
  mutations: {
    ADD_MENUS (state, routes) {
      state.menus = [...routes]
      console.log(state.menus,'menus')
    },
    ADD_disqualificationId (state,value) {
      state.disqualificationId = value
    },
    TOGGLE_SIDEBAR: state => {
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
      state.sidebar.withoutAnimation = false
    },
    INIT_VISITED_VIEWS (state) {
      state.visitedViews = [...state.visitedViews, ...JSON.parse(getStorage('visitedViews'))]
      state.cachedViews = [...state.cachedViews, ...JSON.parse(getStorage('cachedViews'))]
    },
    CLOSE_SIDEBAR: (state, withoutAnimation) => {
      Cookies.set('sidebarStatus', 1)
      state.sidebar.opened = false
      state.sidebar.withoutAnimation = withoutAnimation
    },
    SET_LANGUAGE: (state, language) => {
      state.language = language
      Cookies.set('language', language)
    },
    ADD_VISITED_VIEWS: (state, view) => {
      if (state.visitedViews.some(v => v.path === view.path)) return
      state.visitedViews.push({
        name: view.name,
        path: view.path,
        title: view.meta.title || 'no-name',
        meta: view.meta,
        query: view.query
      })
      setStorage('visitedViews', JSON.stringify(state.visitedViews))
      if (!view.meta.noCache) {
        state.cachedViews.push(view.name)
        setStorage('cachedViews', JSON.stringify(state.cachedViews))
      }
    },
    DEL_VISITED_VIEWS: (state, view) => {
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.path === view.path) {
          state.visitedViews.splice(i, 1)
          break
        }
      }
      for (const i of state.cachedViews) {
        if (i === view.name) {
          const index = state.cachedViews.indexOf(i)
          state.cachedViews.splice(index, 1)
          break
        }
      }
      if (!view.meta.noCache) { 
        setStorage('cachedViews', JSON.stringify(state.cachedViews))
      }
      setStorage('visitedViews', JSON.stringify(state.visitedViews))
    
    },
    DEL_OTHERS_VIEWS: (state, view) => {
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.path === view.path) {
          state.visitedViews = state.visitedViews.slice(i, i + 1)
          break
        }
      }
      for (const i of state.cachedViews) {
        if (i === view.name) {
          const index = state.cachedViews.indexOf(i)
          state.cachedViews = state.cachedViews.slice(index, i + 1)
          break
        }
      }
      if (!view.meta.noCache) { 
        setStorage('cachedViews', JSON.stringify(state.cachedViews))
      }
      setStorage('visitedViews', JSON.stringify(state.visitedViews))
    },
    DEL_ALL_VIEWS: (state) => {
      state.visitedViews = []
      state.cachedViews = []
      if (!view.meta.noCache) { 
        setStorage('cachedViews', JSON.stringify(state.cachedViews))
      }
      setStorage('visitedViews', JSON.stringify(state.visitedViews))
    }
  },
  actions: {
    toggleSideBar({ commit }) {
      commit('TOGGLE_SIDEBAR')
    },
    closeSideBar({ commit }, { withoutAnimation }) {
      commit('CLOSE_SIDEBAR', withoutAnimation)
    },
    setLanguage({ commit }, language) {
      commit('SET_LANGUAGE', language)
    },
    addVisitedViews({ commit }, view) {
      commit('ADD_VISITED_VIEWS', view)
    },
    delVisitedViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit('DEL_VISITED_VIEWS', view)
        resolve([...state.visitedViews])
      })
    },
    delOthersViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit('DEL_OTHERS_VIEWS', view)
        resolve([...state.visitedViews])
      })
    },
    delAllViews({ commit, state }) {
      return new Promise((resolve) => {
        commit('DEL_ALL_VIEWS')
        resolve([...state.visitedViews])
      })
    },
    async getAuthorityMenuList({ commit, state, rootState }) {
      let res
        try {
          res = await getAuthorityMenuList({ managerId: rootState.user.userInfo.managerId })
          if (res.code === 1) {
            let resultRoutes = filterAsyncRouter(asyncRouterMap, res.data)
            console.log('resultRoutes:', resultRoutes)
            commit('ADD_MENUS', resultRoutes)
            res.resultRoutes = resultRoutes
          }
    
          return res
        } catch (error) {
          return error
        }
    }
  }
}

export default app
